package com.henu.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = { "/sync" }, asyncSupported = true)
public class AsyncServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 5771215666658237180L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("start sync");
        AsyncContext asyncCtx = req.startAsync();
        new Thread(new AsyncThread(asyncCtx)).start();
        out.flush();
    }
}

class AsyncThread implements Runnable {
    private final AsyncContext req;

    public AsyncThread(AsyncContext req) {
        this.req = req;
    }

    @Override
    public void run() {
        PrintWriter out=null;
        try {
            Thread.sleep(1000 * 5);
            out = req.getResponse().getWriter();
            out.println("this is in sync");
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}